package dn.easy.common.utils;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * 描述：保存实体类
 * @author yangjing
 * @ClassName:
 * @date  2016.09.29
 */
public class SaveUserInfo extends Application {

    private static final String NAME = "yblShocll";

    @SuppressLint("WrongConstant")
    public static SharedPreferences getSharedPreferences(Context context) {
        return context.getSharedPreferences(NAME, Context.MODE_APPEND);
    }

    /**
     * 保存实体类
     * @param context
     * @param key
     * @param obj
     */
    public static void saveBean(Context context, String key, Object obj) {
        if (obj instanceof Serializable) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(obj);
                String string64 = new String(Base64.encode(baos.toByteArray(), 0));
                SharedPreferences.Editor editor = getSharedPreferences(context).edit();
                editor.putString(key, string64);
                editor.commit();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            throw new IllegalArgumentException("the obj must implement Serializble");
        }
    }

    /**
     * 取出保存的实体类
     * @param context
     * @param key
     * @return
     */
    public static Object getBean(Context context, String key) {
        Object obj = null;
        try {
            String base64 = getSharedPreferences(context).getString(key, "");
            if (base64.equals("")) {
                return null;
            }
            byte[] base64Bytes = Base64.decode(base64.getBytes(), 1);
            ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            obj = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 退出登录
     * @param key
     * @param context
     */
    public static void logOut(Context context, String key) {
        SharedPreferences.Editor editor = getSharedPreferences(context).edit();
        editor.remove(key);
        editor.commit();
    }

}
